
package org.ricks.ioc.definition.filed;

import org.ricks.ioc.cfg.RicksPropertiesLoader;
import org.ricks.ioc.utils.IocException;
import java.lang.reflect.Field;

/**
 * Value方式注入配置参数.
 */
public class ValueFieldDefinition extends DefaultFieldDefinition {
    /**
     * 对应配置文件中的Key...
     */
    private final String key;

    public ValueFieldDefinition(Field field, String key) {
        super(field,key);
        this.key = key;
    }

    /**
     * 配置参数注入，如果没找到则忽略，使用默认值...
     */
    @Override
    public void injection(Object single) {
        String value = RicksPropertiesLoader.get(key);
        if (!value.isBlank()) {
            try {
                field.setAccessible(true);
                field.set(single, conver(value,field.getType()));
            } catch (Exception e) {
                // 静态属性写入时Target会为null
                Class<?> klass = single == null ? field.getDeclaringClass() : single.getClass();
                throw new IocException(klass + " 的 " + field.getName() + " 属性无法注入.", e);
            }
        }
    }

    private Object conver(String value,Class clazz){
        return switch (clazz.getName()) {
            case "byte" -> Byte.valueOf(value);
            case "short" -> Short.parseShort(value);
            case "int" -> Integer.valueOf(value);
            case "float" -> Float.parseFloat(value);
            case "long" -> Long.parseLong(value);
            case "double" -> Double.parseDouble(value);
            case "boolean" -> Boolean.parseBoolean(value);
            default -> String.valueOf(value);
        };
    }
}